package com.yuda.campsite.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;
import java.io.File;
import java.util.Map;
import java.util.Properties;

@Slf4j
@Component
public class SendMailUtil {

    private static final Properties props = new Properties();

    private static Session mailSession;

    public SendMailUtil() {
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtpdm.aliyun.com");
        props.put("mail.smtp.port", "80");
        //smtp登陆
        props.put("mail.user", "notice@service.campcenter.cn");
        props.put("mail.password", "THussat2020");

        //用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };

        // 创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        //mailSession.setDebug(true);
        this.mailSession = mailSession;

    }

    /**
     * mailAdr 收件人地址,多个收件地址用,隔开
     * content 邮件文本内容
     */
    public static void sendMail(Map<String, String> map) {


        log.info("***************邮件发送线程开始****************");
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        try {
            //发件邮箱 props.getProperty("mail.user"),
            String addr = MimeUtility.encodeText("营地项目部");
//            InternetAddress form = new InternetAddress("THUSSAT");
            message.setFrom(new InternetAddress(addr + " < notice@service.campcenter.cn >"));
            // 设置收件人 // 支持群发，多地址用逗号分隔
            message.setRecipients(RecipientType.TO, map.get("mailAdr"));
            // 设置邮件标题
            message.setSubject(map.get("subject"));
            // 设置邮件的内容体
            message.setContent(map.get("content"), "text/html;charset=UTF-8");
            message.saveChanges();
        } catch (Exception e1) {
            log.error("发送邮件出现异常！" + e1.toString());
            e1.printStackTrace();
        }

        // 发送邮件
        log.info("*****发送邮件" + map.get("mailAdr"));
        try {
            Transport.send(message);
//                	jdbcTemplate.update("update th_email set status = 1 where email = '"+map.get("mailAdr")+"'");
        } catch (MessagingException e) {
            log.error("发送邮件出现异常！" + e.toString());
            e.printStackTrace();
        }
        log.info("***************邮件发送线程结束****************");

    }


    /**
     * 发送邮件并带着附件
     *
     * @param map
     */
    public static boolean sendMailWithEnclosure(Map<String, String> map, String filePath) {


        log.info("***************邮件发送线程开始****************");
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);

        //设置邮件内容，混合模式
        MimeMultipart msgMultipart = new MimeMultipart("mixed");

        try {
            //发件邮箱
//            InternetAddress form = new InternetAddress(props.getProperty("mail.user"));

            String addr = MimeUtility.encodeText("THUSSAT");
//            InternetAddress form = new InternetAddress("THUSSAT");
            message.setFrom(new InternetAddress(addr + " < service@kw.thussat.com >"));

//            message.setFrom(form);
            // 设置收件人 // 支持群发，多地址用逗号分隔
            message.setRecipients(RecipientType.TO, map.get("mailAdr"));
            // 设置邮件标题
            message.setSubject(map.get("subject"));


            MimeBodyPart content = new MimeBodyPart();
            content.setContent(map.get("content"), "text/html;charset=UTF-8");
            msgMultipart.addBodyPart(content);
            // 设置邮件的内容体
//            message.setContent(map.get("content"), "text/html;charset=UTF-8");

            //设置邮件内容，混合模式
            message.setContent(msgMultipart);

            //设置相关文件
            File file = new File(filePath);
            if (!file.exists()) {
                log.info("文件不存在 " + filePath);
                return false;
            }
            MimeBodyPart filePart = new MimeBodyPart();
            FileDataSource dataSource = new FileDataSource(file);
            DataHandler dataHandler = new DataHandler(dataSource);
            // 文件处理
            filePart.setDataHandler(dataHandler);
            // 附件名称
            filePart.setFileName("认证成绩单.pdf");

            // 放入正文（有先后顺序，所以在正文后面）
            msgMultipart.addBodyPart(filePart);

            log.info("*****发送邮件" + map.get("mailAdr"));
            // 发送邮件
            Transport.send(message);
        } catch (Exception e1) {
            log.error("发送邮件出现异常！" + e1.toString());
            e1.printStackTrace();
            return false;
        }

        log.info("***************邮件发送线程结束****************");
        return true;
    }

}
